
import { PluginOption } from "vite";
import fs from 'fs';
import path from 'path';
import dayjs from 'dayjs';
import { IncomingMessage, ServerResponse } from "http";

/**
 * 开发接口 ‘/dev/icons’ 返回图标列表
 */
export default function (): PluginOption[] {
    return [{
        name: 'vite-create-icons-dictionary',
        apply: 'serve',
        configureServer(server) {
            server.middlewares.use('/dev/icons/get', (req: IncomingMessage, res: ServerResponse) => {
                try {
                    const list = fs
                        .readdirSync(path.join(__dirname, '../../public/icons'))
                        .filter(e => e.endsWith('.svg'))
                        .map(e => e.replace('.svg', ''))
                        .map(e => `"${e}"`)

                    res.setHeader('Content-Type', 'application/json');
                    res.end(`[${list.join(',')}]`);
                } catch (error: any) {
                    res.statusCode = 500;
                    res.end(`Error: ${error.message || '开发服务器错误'}`);
                }
            });

            server.middlewares.use('/dev/icons/add', (req: IncomingMessage, res: ServerResponse) => {
                try {
                    let body = '';
                    req.on('data', chunk => { body += chunk.toString() });
                    req.on('end', () => {
                        const id = `${dayjs().format('IYYYYMMDDHHmmss')}.svg`;
                        const filePath = path.join(__dirname, '../../public/icons', id);
                        fs.writeFileSync(filePath, body);
                        res.end();
                    });
                } catch (error: any) {
                    res.statusCode = 500;
                    res.end(`Error: ${error.message || '开发服务器错误'}`);
                }
            });
        }
    }]
}